import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '/src/stores/modules/user'

// createRouter 创建路由实例，===> new VueRouter()
// 1. history模式: createWebHistory()   http://xxx/user
// 2. hash模式: createWebHashHistory()  http://xxx/#/user

// vite 的配置 import.meta.env.BASE_URL 是路由的基准地址，默认是 ’/‘
// https://vitejs.dev/guide/build.html#public-base-path

// 如果将来你部署的域名路径是：http://xxx/my-path/user
// vite.config.ts  添加配置  base: my-path，路由这就会加上 my-path 前缀了
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/login/LoginPage.vue') }, //登录页
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/goods/mode',
      children: [
        {
          path: '/goods/manage',
          component: () => import('@/views/goods/GoodsManage.vue')
        },
        {
          path: '/goods/channel',
          component: () => import('@/views/goods/GoodsChannel.vue')
        },
        {
          path: '/goods/mode',
          component: () => import('@/views/goods/GoodsProfile.vue')
        },
        {
          path: '/goods/detail/:id',
          component: () => import('@/views/goods/GoodsDetail.vue')
        },
        {
          path: '/goods/car',
          component: () => import('@/views/goods/GoodsCar.vue')
        },
        {
          path: '/goods/orders',
          component: () => import('@/views/goods/GoodsOrders.vue')
        }
      ]
    },
    {
      path: '/user/profile',
      component: () => import('@/views/user/UserProfile.vue'),
      children: [
        {
          path: '/user/goods',
          component: () => import('@/views/user/UserGoods.vue')
        },
        {
          path: '/user/change',
          component: () => import('@/views/user/UserChange.vue')
        },
        {
          path: '/user/money',
          component: () => import('@/views/user/UserMoney.vue')
        },
        {
          path: '/user/message',
          component: () => import('@/views/user/UserMessage.vue')
        }
      ]
    }
  ]
})
// 登录访问拦截 => 默认直接放行
// 根据返回值决定，是放行还是拦截
//返回值：
//1 undefined / true 直接放行
//2 false 拦截from的地址页面
//3 具体路径 / 路径对象 拦截到对应的地址
// ‘/login’ { name：‘login’ }
router.beforeEach((to) => {
  //如果没有token，且访问的是非登录页，拦截到登录，其他情况正常放行
  const useStore = useUserStore()
  if (!useStore.token && to.path !== '/login') return '/login'
  return true
})
export default router
